package com.zhkj.txg.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.view.View.OnClickListener
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.utils.TextWatcherWrapper
import razerdp.util.KeyboardUtils

class NumberEditView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle) {

    private val itemSize: Int = ScreenUtil.dip(context, 35)

    private val number = EditText(context)
    private val minus = TextView(context)
    private val plus = TextView(context)

    private var type: Int = 0

    private val minusClickListener = OnClickListener {
        val currentNumber = number.text.toString().toInt()
        when {
            currentNumber >= 2 -> {
                val toString = (currentNumber - 1).toString()
                number.setText(toString)
                number.setSelection(toString.length)
                number.clearFocus()
                numberChangeListener?.change(2, currentNumber - 1, maxCount)
                if (KeyboardUtils.isOpen()) KeyboardUtils.close(number)
//                if (numberChangeListener != null) {
//                    numberChangeListener?.change(0, currentNumber, maxCount)
//                } else number.setText((currentNumber - 1).toString())
            }
            else -> Unit
        }
    }
    private val plusClickListener = OnClickListener {
        val currentNumber = number.text.toString().toInt()
        when {
            currentNumber < maxCount -> {
                val toString = (currentNumber + 1).toString()
                number.setText(toString)
                number.setSelection(toString.length)
                number.clearFocus()
                numberChangeListener?.change(2, currentNumber + 1, maxCount)
                if (KeyboardUtils.isOpen()) KeyboardUtils.close(number)
//                if (numberChangeListener != null) {
//                    numberChangeListener?.change(1, currentNumber, maxCount)
//                } else number.setText((currentNumber + 1).toString())
            }
            else -> Unit
        }
    }

    var maxCount: Int = 2000
        set(value) {
            field = value
            when {
                value == 0 -> {
                    number.setText("0")
                    minus.isEnabled = false
                    plus.isEnabled = true
                }
                number.text.toString().toInt() > value -> {
                    number.setText(value.toString())
                    minus.isEnabled = true
                    plus.isEnabled = false
                }
                else -> {
                    minus.isEnabled = true
                    plus.isEnabled = true
                }
            }
        }
    var numberChangeListener: OnNumberChangeListener? = null

    init {
        with(context.obtainStyledAttributes(attrs, R.styleable.NumberEditView)) {
            type = getInt(R.styleable.NumberEditView_ne_type, 0)
            recycle()
        }
        orientation = HORIZONTAL
        gravity = Gravity.CENTER
        if (type != 0) setBackgroundResource(R.drawable.bg_round_5_gray)
        // 添加减按钮
        addView(minus.apply {
            setBackgroundResource(R.drawable.selector_number_edit)
            gravity = Gravity.CENTER
            text = "-"
            textSize = 18F
            setTextColor(ContextCompat.getColorStateList(context, R.color.selector_number_edit))
            setOnClickListener(minusClickListener)
        }, LayoutParams(itemSize, itemSize))
        // 添加数字
        addView(number.apply {
            if (type == 0) setBackgroundResource(R.drawable.bg_round_5_a0a0a0)
            else background = null
            gravity = Gravity.CENTER
            setText("1")
            textSize = 14F
            isEnabled = false
            setSingleLine()
            inputType = EditorInfo.TYPE_CLASS_NUMBER
            imeOptions = EditorInfo.IME_ACTION_DONE
            setTextColor(
                if (type == 0) Color.WHITE
                else ContextCompat.getColor(context, R.color.colorMain)
            )
            // 重构显示的数据
            addTextChangedListener(TextWatcherWrapper {
                when {
                    it.isNullOrEmpty() -> {
                        setText("0")
                        setSelection(1)
                    }
                    it.toString().length > 1 && it.toString().startsWith("0") -> {
                        it.delete(0, 1)
                        setSelection(1)
                    }
                    it.toString().toInt() > maxCount -> {
                        it.replace(0, it.length, maxCount.toString())
                        setSelection(maxCount.toString().length)
                    }
                }
            })
            setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    numberChangeListener?.change(2, number.text.toString().toInt(), maxCount)
                    true
                }
                false
            }
        }, LayoutParams(itemSize, itemSize).apply {
            gravity = Gravity.CENTER
            marginStart = if (type == 0) 10 else 0
            marginEnd = if (type == 0) 10 else 0
        })
        // 添加加按钮
        addView(plus.apply {
            setBackgroundResource(R.drawable.selector_number_edit)
            gravity = Gravity.CENTER
            text = "+"
            textSize = 18F
            if (type == 0) setTextColor(
                ContextCompat.getColorStateList(
                    context,
                    R.color.selector_number_edit
                )
            )
            else setTextColor(ContextCompat.getColor(context, R.color.colorMain))
            setOnClickListener(plusClickListener)
        }, LayoutParams(itemSize, itemSize))
    }

    fun currentNumber(): Int = number.text.toString().toInt()

    fun setCurrentNumber(numb: Int) {
        number.setText(numb.toString())
    }
}

interface OnNumberChangeListener {
    /**
     * 点击事件(type - 0:减按钮 1:加按钮 2:数字)
     */
    fun change(type: Int, originNumber: Int, maxCount: Int)
}